package com.attcatstudy.Thread;

/**
 * @author attcat
 * ---做一个有趣的程序员
 * @date 2022-10-29 15:28
 * @description  抢票的小mode
 */
public class SellTicketDemo implements Runnable {

    /**
     *车票
     */
    private int ticket= 1000;


    @Override
    public void run() {
        while (ticket>0){
            synchronized (this){
                if (ticket>0){
                // 线程进入暂时的休眠
                    try {
                        Thread.sleep(2);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(Thread.currentThread().getName() + ":正在执行操作，余票:" + ticket--);
                }
            }
            if(ticket==0){
                System.out.println(Thread.currentThread().getName() + ":没有票了，余票:" + ticket);
            }
            //yield会释放CPU资源，让当前线程从 Running 进入 Runnable状态，让优先级更高 (至少是相同)的线程获得执行机会，不会释放对象锁;
            Thread.yield();
        }

    }


    public static void main(String[] args) {
        SellTicketDemo demo = new SellTicketDemo();
        Thread thread1 = new Thread(demo,"thread1");
        Thread thread2 = new Thread(demo,"thread2");
        Thread thread3 = new Thread(demo,"thread3");
        Thread thread4 = new Thread(demo,"thread4");
        thread1.setPriority(Thread.MIN_PRIORITY);
        thread2.setPriority(Thread.MAX_PRIORITY);
        thread3.setPriority(Thread.NORM_PRIORITY);
        thread4.setPriority(Thread.NORM_PRIORITY);
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();

    }

}
